﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;

namespace GenerateFilesLibrary
{
   public class GenerateFiles
    {
        public bool generateRootFiles()
        {
            bool result = false;
            try
            {
                string rootDirectory = AppDomain.CurrentDomain.BaseDirectory;
                rootDirectory = rootDirectory.Replace("\\GenerateFiles\\bin\\Debug\\", "");

                String rootdataFolder = rootDirectory+"\\CoreData\\";
                if (Directory.Exists(rootdataFolder))
                {
                    Directory.Delete(rootdataFolder, true);
                }
                Directory.CreateDirectory(rootdataFolder);
                DownloadFilesFromFTP(rootdataFolder);

                if (File.Exists(rootDirectory + "\\GetCountryFromIP\\IpData\\IPCountry.txt"))
                {
                    File.Delete(rootDirectory + "\\GetCountryFromIP\\IpData\\IPCountry.txt");
                }

                if (Directory.Exists(rootDirectory + "\\GetCountryFromIP\\IpData"))
                {
                    Directory.Delete(rootDirectory + "\\GetCountryFromIP\\IpData", true);
                }
                Directory.CreateDirectory(rootDirectory + "\\GetCountryFromIP\\IpData");

               ReadFile(rootdataFolder + "north-America.txt", @"arin\|(.)*\|ipv4\|(.)*\|(.)*\|(.)*\|a");
               ReadFile(rootdataFolder + "Asia.txt", @"apnic\|(.)*\|ipv4\|(.)*\|(.)*\|(.)*\|a");
               ReadFile(rootdataFolder + "latinAmerica.txt", @"lacnic\|(.)*\|ipv4\|(.)*\|(.)*\|(.)*\|a");
               ReadFile(rootdataFolder + "africa.txt", @"afrinic\|(.)*\|ipv4\|(.)*\|(.)*\|(.)*\|a");
               ReadFile(rootdataFolder + "europe.txt", @"ripencc\|(.)*\|ipv4\|(.)*\|(.)*\|(.)*\|a");

                //p.Europe = ReadFile(rootdataFolder + "Test.txt", @"arin\|(.)*\|ipv4\|(.)*\|(.)*\|(.)*\|a");
                result = true;
            }
            catch(Exception ex)
            {
                result = false;
            }
            return result;
            
        }

        public static void ReadFile(string filename, string expression)
        {

            System.IO.StreamReader myFile = new System.IO.StreamReader(filename);
            string myString = myFile.ReadToEnd();

            myFile.Close();

            MatchCollection col = Regex.Matches(myString, expression);
            Dictionary<string, string> dicOfIPCountry = new Dictionary<string, string>();

            Dictionary<string, string> CountryIPStr = new Dictionary<string, string>();

            StringBuilder key_country = new StringBuilder();

            string prevCountry = "";
            foreach (Match c in col)
            {
                string capturedValue = c.Value;
                String ip = Regex.Match(capturedValue, @"[0-9]*\.(.)*\.(.)*\.[0-9]*").Value;
                string country = Regex.Match(capturedValue, @"[A-Z]+").Value;

                string key = ip.Split('.')[0] + "." + ip.Split('.')[1];
                if (!dicOfIPCountry.ContainsKey(key))
                {
                    dicOfIPCountry.Add(key, country);
                    key_country.AppendLine("[" + ip + "]" + "##" + country + @"@@");
                }
                else
                {
                    if (prevCountry != country)
                    {
                            key = ip.Split('.')[0] + "." + ip.Split('.')[1] + "." + ip.Split('.')[2];
                            if (!dicOfIPCountry.ContainsKey(key))
                            {
                                dicOfIPCountry.Add(key, country);
                                key_country.AppendLine("[" + ip + "]" + "##" + country + @"@@");
                            }
                    }
                }
                prevCountry = country;
            }

            //String countryFileName = filename.Replace("C:\\Pavan\\My Stuff\\Code Samples\\GetCountryFromIP\\GETCountryFromIP\\CoreData\\", "");
            //string path = @"C:\Pavan\My Stuff\Code Samples\GetCountryFromIP\GETCountryFromIP\GETCountryFromIP\IpData\" + countryFileName;

            //if (!File.Exists(path))
            //{
            //    using (StreamWriter sw = File.CreateText(path))
            //    {
            //        sw.Write(key_country.ToString());
            //    }
            //}
            //else
            //{
            //    using (StreamWriter sw = File.AppendText(path))
            //    {
            //        sw.Write(key_country.ToString());
            //    }
            //}

          string  rootDirectory = AppDomain.CurrentDomain.BaseDirectory;
            rootDirectory = rootDirectory.Replace("\\GenerateFiles\\bin\\Debug\\", "");

            string Ippath = rootDirectory + "\\GetCountryFromIP\\IpData\\IPCountry.txt";

            if (!File.Exists(Ippath))
            {
                using (StreamWriter sw = File.CreateText(Ippath))
                {
                    sw.Write(key_country.ToString());
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(Ippath))
                {
                    sw.Write(key_country.ToString());
                }
            }
        }

       public void DownloadFilesFromFTP(string writePath)
       {
           string localPath = writePath;

           Dictionary<string, string> dicIPFiles = new Dictionary<string, string>();
           dicIPFiles.Add("europe.txt", "ftp://ftp.arin.net/pub/stats/ripencc/delegated-ripencc-latest");
           dicIPFiles.Add("latinAmerica.txt", "ftp://ftp.arin.net/pub/stats/lacnic/delegated-lacnic-latest");
           dicIPFiles.Add("north-America.txt", "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-latest");
           dicIPFiles.Add("Asia.txt", "ftp://ftp.arin.net/pub/stats/apnic/delegated-apnic-latest");
           dicIPFiles.Add("africa.txt", "ftp://ftp.arin.net/pub/stats/afrinic/delegated-afrinic-latest");


           foreach (KeyValuePair<string, string> keyValue in dicIPFiles)
           {
               string fileName = keyValue.Key;
               string serverPath = keyValue.Value;
               FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(serverPath);
               requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

               FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();

               Stream responseStream = responseFileDownload.GetResponseStream();
               FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create);

               int Length = 2048;
               Byte[] buffer = new Byte[Length];
               int bytesRead = responseStream.Read(buffer, 0, Length);

               while (bytesRead > 0)
               {
                   writeStream.Write(buffer, 0, bytesRead);
                   bytesRead = responseStream.Read(buffer, 0, Length);
               }

               responseStream.Close();
               writeStream.Close();

               requestFileDownload = null;
               responseFileDownload = null;

           }
       }
    }
}
